package com.wumai.keystrokes.renders;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.platform.GlStateManager;
import com.wumai.keystrokes.models.Position;
import com.wumai.keystrokes.models.display.TextureResource;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.renderer.texture.TextureManager;

import static net.minecraft.util.math.MathHelper.floor;

public class RenderKeyOnScreen extends AbstractGui {

    private MatrixStack matrixStack;
    private Minecraft minecraftInstance;

    public RenderKeyOnScreen(MatrixStack matrixStack) {
        this.matrixStack = matrixStack;
        this.minecraftInstance = Minecraft.getInstance();
    }

    private void renderTextureResource(float x, float y, float width, float height, TextureResource textureResource) {
        if (textureResource == null || textureResource.getResourceLocation() == null) {
            return;
        }
        
        TextureManager textureManager = minecraftInstance.getTextureManager();
        textureManager.bind(textureResource.getResourceLocation());
        
        int windowWidth = minecraftInstance.getWindow().getGuiScaledWidth();
        int windowHeight = minecraftInstance.getWindow().getGuiScaledHeight();
        
        int _x1 = floor(windowWidth * (x + 1.0f) / 2);
        int _y1 = floor(windowHeight * (y + 1.0f) / 2);
        int _width = floor(windowWidth * width / 2);
        int _height = floor(windowHeight * height / 2);
        
        // 修复：使用正确的blit方法签名来绘制纹理的一部分
        // blit(MatrixStack, int x, int y, int width, int height, float u, float v, int uWidth, int vHeight, int textureWidth, int textureHeight)
        blit(matrixStack, _x1, _y1, _width, _height, 
             textureResource.getU(), textureResource.getV(), 
             textureResource.getWidth(), textureResource.getHeight(), 
             textureResource.getTextureWidth(), textureResource.getTextureHeight()); // 256x256是默认纹理图集的尺寸
    }
    
    public void renderKeyOnScreen(TextureResource textureResource, Position position, float width, float height) {
        GlStateManager._enableBlend();
        // 绘制纹理资源
        if (textureResource != null) {
            this.renderTextureResource(position.getX(), position.getY(), width, height, textureResource);
        }
        GlStateManager._disableBlend();
    }
}